import React, { useState, useEffect } from 'react';
import { Button, Divider, Modal } from 'antd';
import { useHistory } from 'react-router-dom';
import { LoadingOutlined, RollbackOutlined } from '@ant-design/icons';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  combile_mxdata_mxcol_util,
  convertISODateTimeToYYYYMMDDHHMMSS,
  use_dict_byzdmc,
  dealnullorundenfined,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import { use_wlda_initformdata, use_wlda_mx_column_initformdata, use_wlfl_treedata } from './use_baseinfo_config.js';
import Wlda_form_wlfl from './wlda_form_wlfl'

moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import Wlda_mx_hook from './wlda_mx_hook.js';


const Wlda_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    wlda_cp: [], wlda_mj: [],
    dict_dw: []
  })
  const treeData = use_wlfl_treedata()


  //主表数据
  const [formdata, setformdata] = useState(use_wlda_initformdata)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [mxdata, setmxdata] = useState([])
  const [delidarr, setdelidarr] = useState([]);
  const [mxcolums, setmxcolums] = useState(use_wlda_mx_column_initformdata)
  const [isloading, setisloading] = useState(true)
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();

  /**
  * 强制刷新明细表 用于特殊场景
  */
  const [switche, setswitche] = useState(true);
  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])

  //加载主表数据
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/baseinfo/query_wlda_byid", 'POST', { id }, "json")
    console.log(rtdata.resultdata.formdata)
    var newformdata = resultdata_to_formdata(rtdata.resultdata.formdata, formdata)
    let mxdatares = rtdata.resultdata.mxdata;
    mxdatares.forEach(element => {
      element.gmsj = element.gmsj == null ? '' : convertISODateTimeToYYYYMMDDHHMMSS(element.gmsj)
    })
    var newmxdata = addkey_for_mxdata(mxdatares)
    setmxdata(newmxdata);
    
    // 使用当前表单中的树数据，而不是从storage获取
    newformdata.lbmc.selectdata = formdata.lbmc.selectdata
    newformdata.lbmc.inputType = "readonly"
    setformdata({ ...formdata, ...newformdata });
  }



  // 构建物料分类树形结构（按照 wlda_list.js 的方式）
  const buildWlflTree = (wlflData) => {
    // 创建根节点
    const rootNode = {
      title: '企业物料总目',
      label: '企业物料总目', // 添加 label 属性
      value: 'ship',
      key: 'ship',
      level: 0,
      data: null, // 根节点不需要具体的分类数据
      children: []
    }

    // 递归构建树形结构
    const buildTreeRecursive = (parentKey, parentLevel) => {
      const children = []
      
      wlflData.forEach(wlfl => {
        // 根据编码规则判断是否为当前父节点的子节点
        let isChild = false
        
        if (parentKey === 'ship') {
          // 根节点的子节点：一级分类 (ship.01, ship.02, ...)
          isChild = wlfl.flbm.match(/^ship\.\d+$/)
        } else {
          // 其他节点的子节点：直接子分类 (parentKey.01, parentKey.02, ...)
          const childPattern = new RegExp(`^${parentKey.replace(/\./g, '\\.')}\\.\\d+$`)
          isChild = childPattern.test(wlfl.flbm)
        }
        
        if (isChild) {
          const childNodes = buildTreeRecursive(wlfl.flbm, parentLevel + 1)
          const node = {
            title: `${wlfl.flmc}`,
            label: wlfl.flmc, // 添加 label 属性
            key: wlfl.flbm,
            level: parentLevel + 1,
            value: wlfl.flbm,
            data: wlfl
          }
          
          // 只有当有子节点时才添加children属性
          if (childNodes.length > 0) {
            node.children = childNodes
          }
          
          children.push(node)
        }
      })
      
      return children
    }

    // 构建完整的树形结构
    rootNode.children = buildTreeRecursive('ship', 0)
    
    return [rootNode]
  }

  // 处理树状数据（按照 wlda_list.js 的方式）
  const processTreeData = (data) => {
    return data.map(item => ({
      ...item,
      value: item.key,
      children: item.children && item.children.length > 0 ? processTreeData(item.children) : undefined
    }));
  }

  const querywltree = async () => {
    try {
      // 按照 wlda_list.js 的方式调用 API
      let rtdata = await fetchsync_util("/admin/baseinfo/wlfllb", 'POST', {}, "json")
      
      const processedData = dealnullorundenfined(rtdata.resultdata)
      
      // 构建树形结构
      const treeDataFromApi = buildWlflTree(processedData)
      
      // 处理树状数据
      const processedTreeData = processTreeData(treeDataFromApi)
      
      let newformdata = { ...formdata }
      newformdata.lbmc.selectdata = processedTreeData;
      // 页面加载时不设置默认值，让用户手动选择分类
      newformdata.lbmc.value = ""
      setformdata({ ...newformdata })
    } catch (error) {
      console.error('查询分类失败:', error);
      openNotification_util('查询分类失败，请稍后重试');
    }
  }

  //加载主表数据 复制模式清除物料编码
  const loadformdatacopy = async (id) => {
    let rtdata = await fetchsync_util("/admin/baseinfo/query_wlda_byid", 'POST', { id }, "json")
    console.log(rtdata.resultdata.formdata)
    var newformdata = resultdata_to_formdata(rtdata.resultdata.formdata, formdata)
    // 使用当前表单中的树数据，而不是从storage获取
    newformdata.lbmc.selectdata = formdata.lbmc.selectdata
    // 复制模式下清空物料编码和分类选择，让用户重新选择
    newformdata.wlbm.value = ""
    newformdata.lbmc.value = ""
    newformdata.lbbm.value = ""
    setformdata({ ...formdata, ...newformdata });
  }



  //初始化树数据
  const init = async () => {
    // 先加载分类树数据
    await querywltree()
    
    var dictObj = await use_dict_byzdmc(["dict_dw"])
    dynDatasObject.dict_dw = dictObj.dict_dw
    setdynDatasObject({ ...dynDatasObject })
    setisloading(false)
  }


  // 页面进入加载数据
  useEffect(() => {
    const loadData = async () => {
      // 先初始化（包括加载树数据）
      await init()
      
      // 然后根据类型加载主表数据
      if (JSON.parse(storage.pre_wlda_item).type == "edit") {
        await loadformdata(JSON.parse(storage.pre_wlda_item).data.id)
      } else if (JSON.parse(storage.pre_wlda_item).type == "copy") {
        await loadformdatacopy(JSON.parse(storage.pre_wlda_item).data.id)
      }
    }
    
    loadData()
  }, [])


  //设置value
  const setfield = (onekey, value, settype) => {

    if (settype == 'single') {
      if (onekey == 'lbmc') {
        let newformdata = { ...formdata }
        // 处理树选择，value 是选中的节点对象
        if (value && value.title) {
          newformdata.lbmc.value = value.title
          newformdata.lbbm.value = value.key
          console.log('设置分类:', { title: value.title, key: value.key })
        } else if (typeof value === 'string') {
          // 处理 TreeSelect 的字符串值
          newformdata.lbmc.value = value
          newformdata.lbbm.value = value
          console.log('设置分类字符串值:', value)
        }
        setformdata(newformdata)

      }
      else {

        var newitem = formdata[onekey]
        newitem.value = value
        let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
        setformdata(newformdata)
      }

    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }


  const handleupload = async () => {

    var checkobj = checkdatavalid_util_formdata(formdata)
    //拼接明细
    var newmxdatalist = combile_mxdata_mxcol_util(mxdata, mxcolums)
    //主表字段校验没通过不能保存，目前没写子表校验。

    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage); return; }
    else;
    //设置submit url
    var uploadurl = JSON.parse(storage.pre_wlda_item).type == "add" || JSON.parse(storage.pre_wlda_item).type == "copy" ?
      "/admin/baseinfo/add_wlda" : "/admin/baseinfo/update_wlda";
    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata, delidarr, mxdata: newmxdatalist }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
    dropByCacheKey('wldalb')
    dropByCacheKey('wlda_form')
    setnowroute({ route: "/shipSRM/baseinfo/wldalb", title: "物料档案", closeroute: "/shipSRM/baseinfo/wlda_form" })
  }


  //返回列表
  const handleBackTolist = () => {
    dropByCacheKey('wlda_form')
    setnowroute({ route: "/shipSRM/baseinfo/wldalb", title: "物料档案", closeroute: "/shipSRM/baseinfo/wlda_form" })
  }

  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}
      data-page-type="form">

<div style={{width:"100%",height:"100%",backgroundColor:"white"}}>
      <Modal destroyOnClose={true} open={isModalOpen} title="物料分类树"
        onCancel={() => { setIsModalOpen(false) }} width="90%" footer={null}
        style={{ backgroundColor: "rgba(0,0,0,0.8)" }}
        bodyStyle={{ borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}>
        <Wlda_form_wlfl />
      </Modal>

      {isloading && (
        <div style={{
          position: 'absolute',
          top: '1%',
          left: 0,
          width: '100%',
          height: '98%',
          backgroundColor: 'rgba(0,0,0,0.1)',
          zIndex: 999
        }} />
      )}

      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%",  backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24",
      }}>
        <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>
        <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          {JSON.parse(storage.pre_wlda_item).type == "edit" || JSON.parse(storage.pre_wlda_item).type == "add" ?
            <Button type="primary" onClick={handleupload}
              style={{ width: "8vw", height: '2.2vw', fontSize: "1vw", borderRadius: "5px", marginTop: "0.4vw" }}>
              <SaveOutlined />{JSON.parse(storage.pre_wlda_item).type == "add" ? "保存" : "修改"}</Button> : <Button type="default" onClick={handleBackTolist}
                style={{ width: "8vw", height: '2.2vw', fontSize: "1vw", borderRadius: "5px", marginTop: "0.4vw" }}>
              <RollbackOutlined />返回列表</Button>}
        </div>
      </div>


      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
        <Divider></Divider>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
            :
            <div style={{ position: "relative", width: "100%", overflowX: "auto", }}>
              {switche && <Wlda_mx_hook colmuns={mxcolums} datasource={mxdata}

                onepageheight="10vh"
                styleobj={{ height: "70%" }}
                dynDatasObject={dynDatasObject}
                formdata={formdata}
                handledelid={ids => { ids.length !== 0 ? setdelidarr([...delidarr, ...ids]) : ''; }}
                handgetmxdata={(tabledata) => {
                  addkey_for_mxdata(tabledata)
                  setmxdata(tabledata)
                }}
                ifshowaddbtn={JSON.parse(storage.pre_wlda_item).type != "view" ? true : false}
                handlechangeFormdata={(data) => {
                  setformdata(data)
                }}
                forceupdate={forceupdate}
              />}</div>
          }

        </div>
      </div>
      </div>

    </div>
  )
}


export default Wlda_form

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1vw", paddingRight: "1vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  kshcontainer: {
    width: "98%", position: "absolute", top: "10%", backgroundColor: "white", color: "#666",
    borderRadius: "10px",paddingBottom:"2rem",overflow:"hidden"
  },
  kshcontainerleft: {
    width: "24%", height: "90%", position: "absolute", top: "3vh", left: "0vw", backgroundColor: "#f7f8fa", color: "black",
    borderRadius: "10px",
  },
}
